package com.zxy.config.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {
    @Value("${config.jwt.secret}")
    private String secret;
    @Value("${config.jwt.expire}")
    private long expire;

    /**
     * 生成token
     */
    public String createToken (Map<String,Object> map){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);//过期时间

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setClaims(map)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解密token 获取数据
     */
    public Claims parseToken(String token){
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    /**
     * 判断是否过期
     */
    public boolean isExpired (Date expirationTime) {
        return expirationTime.before(new Date());
    }
    /**
     * 获取过期时间
     */
    public Date getExpirationDate(String token) {
        return parseToken(token).getExpiration();
    }

    /**
     * 获取签发token的时间
     */
    public Date getIssueDate(String token){
        return parseToken(token).getIssuedAt();
    }
}
